package com.juhui.macao;


import android.app.Application;

import java.io.IOException;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * 140.95
 * Created by LiJianfei on 2016/8/4.
 */
public class RetrofitUtil {
    @Deprecated
    private static <T> T addUrlApi(Application application, String baseUrl, final Class<T> service) {
//        OkHttpClient sClient = new OkHttpClient();
        Retrofit.Builder builder = new Retrofit.Builder();
        OkhttpIntercaptor interceptor = new OkhttpIntercaptor("zhtw", "3bc382de-57b1-4efa-9b04-d0b21e9be9a8");
        OkHttpClient httpClient = new OkHttpClient.Builder()
                .addInterceptor(interceptor)
                .build();
        httpClient.sslSocketFactory();
        Retrofit retrofit = builder.baseUrl(baseUrl).
                addConverterFactory(GsonConverterFactory.create())
//                addConverterFactory(StringToIntConverter.create())
                .client(httpClient).build();
        return retrofit.create(service);
    }


    public static <T> T addUrlApi(Application application, final Class<T> service) {
        return addUrlApi(application, UrlManager.Host, service);
    }

    static class OkhttpIntercaptor implements Interceptor {

        private String mLanguage;
        private String mToken;
        private Application mContext;

        OkhttpIntercaptor(String language, String token) {
            mToken = token;
            mLanguage = language;
        }

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request oldRequest = chain.request();

            // 添加新的参数
            HttpUrl.Builder authorizedUrlBuilder = oldRequest.url()
                    .newBuilder()
                    .scheme(oldRequest.url().scheme())
                    .host(oldRequest.url().host())
                    .addQueryParameter("token", mToken)
                    .addQueryParameter("lang", mLanguage);

            // 新的请求
            Request newRequest = oldRequest.newBuilder()
                    .method(oldRequest.method(), oldRequest.body()).addHeader("Accept-Language", "zh-CN")
                    .url(authorizedUrlBuilder.build())
                    .build();

            return chain.proceed(newRequest);
        }
    }

}
